<?php

namespace jjl\yii2\db;

class Helper {

    const SERVER_ID = 0;

    static public function uuid(string $salt = null) {
        $id = self::SERVER_ID;
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float) sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        if (!$salt)
            $salt = mt_rand(1111, 9999);
        $plaintext = "{$id}#{$msectime}#{$salt}";
        $ciphertext = strtoupper(md5($plaintext));
        $uuid[] = substr($ciphertext, 0, 8);
        $uuid[] = substr($ciphertext, 8, 4);
        $uuid[] = substr($ciphertext, 12, 4);
        $uuid[] = substr($ciphertext, 16, 4);
        $uuid[] = substr($ciphertext, 20);
        return implode('-', $uuid);
    }

    /**
     * 判断输入$string是否为UUID
     * @param type $string
     * @return bool
     */
    static public function is_uuid($string): bool {
        if (strlen($string) == 36 && substr($string, 8, 1) == '-' &&
                substr($string, 13, 1) == '-' &&
                substr($string, 18, 1) == '-' &&
                substr($string, 23, 1) == '-')
            return true;
        else
            return false;
    }

    /**
     * 转为驼峰表示法
     * @param string $name
     * @return string
     */
    static function hump(string $name): string {
        return preg_replace_callback('/(_)([a-z])/', function($r) {
            return strtoupper($r[2]);
        }, $name);
    }

    /**
     * 转为非驼峰表示法
     * @param string $name
     * @return string
     */
    static function unhump(string $name): string {
        return strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $name));
    }

    /**
     * 
     * @param string $table
     * @param \yii\db\Connection $db
     */
    static public function tableExists(string $table, \yii\db\Connection $db) {
        // mysql:host=127.0.0.1;dbname=tcfkw_v2log
        preg_match('/.*dbname=([a-z0-9_]+)$/i', $db->dsn, $databaseName);
        if (!($key = $databaseName[1] ?? null))
            return false;
        $tables = $db->createCommand("show tables ")->queryAll();
        return in_array($table, array_column($tables, "Tables_in_{$key}"));
    }

}
